package job

import (
	"gcrontab/common"
	"github.com/coreos/etcd/clientv3"
	"time"
)

type JobMgr struct {
	client  *clientv3.Client
	kv      clientv3.KV
	lease   clientv3.Lease
	watcher clientv3.Watcher
}

var G_jobMgr *JobMgr

//etcd连接初始化
func InitJob() (err error) {
	//初始化配置
	config := clientv3.Config{
		Endpoints:   common.G_conifg.EtcdEndpoints,
		DialTimeout: time.Duration(common.G_conifg.EtcdDialTimeout) * time.Millisecond,
	}
	//建立连接
	cli, err := clientv3.New(config)
	if err != nil {
		return err
	}
	kv := clientv3.NewKV(cli)
	lease := clientv3.Lease(cli)
	watcher := clientv3.NewWatcher(cli)
	//赋值单例
	G_jobMgr = &JobMgr{
		client:  cli,
		kv:      kv,
		lease:   lease,
		watcher: watcher,
	}

	//启动任务监听 （MARK1）
	if err = G_jobMgr.watchJobs(); err != nil {
		return
	}

	//启动任务监听
	if err = G_jobMgr.watchKiller(); err != nil {
		return
	}

	return
}
